package cn.mabach.oauth2.qq;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;


/**
 * @Author: ming
 * @Date: 2020/2/2 0002 下午 8:27
 */

@Component
public class QQSecurityConfig extends  SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private UserDetailsService qqUserDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        QQAuthenticationFilter qqAuthenticationFilter=new QQAuthenticationFilter();
        qqAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
        qqAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);

        // 获取容器中已经存在的AuthenticationManager对象，并传入 SmsCodeAuthenticationFilter 里面
        qqAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        // 构建一个SmsCodeAuthenticationSecurityConfig实例，传入 UserDetailsService
        QQAuthenticationProvider provider=new QQAuthenticationProvider();
        provider.setUserDetailsService(qqUserDetailsService);

        // 将provider绑定到 HttpSecurity上，并将 smsCodeAuthenticationFilter绑定到用户名密码认证过滤器之后
        http.authenticationProvider(provider)
                .addFilterAfter(qqAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}
